import {
  ProFormDateTimePicker,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
} from '@ant-design/pro-components';
import { Modal, Form, Input, Select, InputNumber, message } from 'antd';
import React, { useImperativeHandle } from 'react';
import randomString from '@/utils/randomString';
import { createUser, updateUser } from '@/services/api/user';

const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const UpdateForm = (props, ref) => {
  const { data, onSuccess } = props;
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    form: form,
  }));
  const onFinish = (values) => {
    if (data) {
      updateUser({ id: data.id, ...values }).then((res) => {
        if (res?.code === 0) {
          onSuccess();
          message.success(res.msg || '操作成功');
        } else {
          message.error(res.msg || '修改失败');
        }
      });
    } else {
      createUser({ ...values, price: Number(values.price) }).then((res) => {
        if (res?.code === 0) {
          onSuccess();
          message.success(res.msg || '操作成功');
        } else {
          message.error(res.msg || '创建失败');
        }
      });
    }
  };
  return (
    <Form
      {...layout}
      form={form}
      name="control-hooks"
      initialValues={
        data
          ? { ...data, password: undefined, apiPassword: undefined }
          : { password: randomString(), apiPassword: randomString() }
      }
      onFinish={onFinish}
    >
      {!data && (
        <Form.Item name="username" label="用户名" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      )}
      {!data && (
        <Form.Item name="price" label="单价" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      )}
      <Form.Item name="password" label="密码" rules={[{ required: !data }]}>
        <Input />
      </Form.Item>
      <Form.Item
        name="apiPassword"
        label="api密码"
        rules={[{ required: !data }]}
      >
        <Input />
      </Form.Item>

      <Form.Item name="phone" label="手机号">
        <Input />
      </Form.Item>
      <Form.Item name="remark" label="备注">
        <Input.TextArea rows={3} maxLength={32} />
      </Form.Item>
    </Form>
  );
};

export default React.forwardRef(UpdateForm);
